package com.lannuokeji.config.shiro;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;

import com.lannuokeji.biz.ac.entity.Resources;
import com.lannuokeji.biz.ac.entity.User;
import com.lannuokeji.biz.ac.service.ResourcesService;
import com.lannuokeji.biz.ac.service.UserService;

public class MyRealm extends AuthorizingRealm {

	@Resource
	private UserService userService;
	@Resource
	private ResourcesService resourcesService;
	
	// 权限过滤
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String userId = (String) principals.getPrimaryPrincipal();
		Map<String, Object> map = new HashMap<>();
		map.put("userid", userId);
		// 获取当前用户的所有可操作的uri
		List<Resources> resourceList = resourcesService.loadUserResources(map);
		// 权限信息对象info,用来存放查出的用户的所有的角色（role）及权限（permission）
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		for (Resources r : resourceList) {
			System.out.println(r);
			if (r.getUri() != null) {	
				authorizationInfo.addStringPermission(r.getUri());
			}
		}
		return authorizationInfo;
	}

	/**
	 * 该方法主要执行以下操作:
		1、检查提交的进行认证的令牌信息
		2、根据令牌信息从数据源(通常为数据库)中获取用户信息
		3、对用户信息进行匹配验证。
		4、验证通过将返回一个封装了用户信息的AuthenticationInfo实例。
		5、验证失败则抛出AuthenticationException异常信息。
	 */
	// 登录身份认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		// 获取用户输入的账号
		UsernamePasswordToken token = (UsernamePasswordToken)authcToken;
//		String username = (String) token.getPrincipal();
		
		User user = userService.login(token.getUsername(), String.valueOf(token.getPassword()));
		
		if (user == null) {// 密码错误
			throw new AuthenticationException();
		}
		token.setRememberMe(false);
		// 通过username从数据库中查找User对象
		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
				token.getUsername(), user.getPassword(), // ByteSource.Util.bytes(user.getEmail()),//salt=username+salt,
				getName());
		// 当验证都通过后，把用户信息放在session里
		Session session = SecurityUtils.getSubject().getSession();
		session.setAttribute("userSession", user);
//        session.setAttribute("userSessionId", user.getId());
		return authenticationInfo;
	}

}
